using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Threading.Tasks;

namespace RiceShop.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class FileUploadManageController : ControllerBase
    {
        private readonly IWebHostEnvironment _hostingEnvironment;

        public FileUploadManageController(IWebHostEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        [HttpPost("upload")]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest(new { result = false, message = "未检测到上传的文件" });
                }

                // 验证文件大小（例如：10MB 限制）
                if (file.Length > 10 * 1024 * 1024)
                {
                    return BadRequest(new { result = false, message = "文件大小不能超过 10MB" });
                }

                // 修改上传路径以匹配Program.cs中的配置
                var uploadBaseDir = Path.Combine(_hostingEnvironment.ContentRootPath, "upload");
                if (!Directory.Exists(uploadBaseDir))
                {
                    Directory.CreateDirectory(uploadBaseDir);
                }

                // 构建保存路径
                var datePath = DateTime.Now.ToString("yyyyMMdd");
                var uploadDir = Path.Combine(uploadBaseDir, datePath);
                
                // 确保上传目录存在
                if (!Directory.Exists(uploadDir))
                {
                    Directory.CreateDirectory(uploadDir);
                }

                // 生成文件名
                var fileName = $"{Path.GetFileNameWithoutExtension(file.FileName)}_{DateTime.Now:HHmmss}{Path.GetExtension(file.FileName)}";
                var filePath = Path.Combine(uploadDir, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 返回成功响应，使用正确的访问路径
                return Ok(new
                {
                    result = true,
                    message = "文件上传成功",
                    filePath = $"/upload/{datePath}/{fileName}"
                });
            }
            catch (Exception ex)
            {
                // 添加更详细的错误信息
                var errorMessage = $"文件上传失败: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMessage += $" Inner exception: {ex.InnerException.Message}";
                }
                errorMessage += $" WebRootPath: {_hostingEnvironment.WebRootPath}";
                
                return StatusCode(500, new { result = false, message = errorMessage });
            }
        }

        [HttpGet("template")]
        public IActionResult DownloadTemplate()
        {
            try
            {
                var templatePath = Path.Combine(_hostingEnvironment.WebRootPath, "templates", "import-template.xlsx");
                if (!System.IO.File.Exists(templatePath))
                {
                    return NotFound(new { result = false, message = "模板文件不存在" });
                }

                var memory = new MemoryStream();
                using (var stream = new FileStream(templatePath, FileMode.Open))
                {
                    stream.CopyTo(memory);
                }
                memory.Position = 0;

                return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "导入模板.xlsx");
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { result = false, message = $"模板下载失败: {ex.Message}" });
            }
        }
    }
}
